package ge.pol.icmia.vano.flashlight.app;

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.hardware.Camera;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.Toast;

import java.io.IOException;


public class MainActivity extends ActionBarActivity implements SurfaceHolder.Callback {
	private Context context = null;
	private static boolean turnedOn = false;
	private static boolean ledOn = false;
	private static Camera camera = null;
	public ImageButton lightButton = null;
	private SurfaceHolder surfaceHolder = null;
	private static View rootView = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		if (savedInstanceState == null) {
			getSupportFragmentManager().beginTransaction()
					.add(R.id.container, new PlaceholderFragment())
					.commit();
		}
		context = getApplicationContext();
//		lightButton = (ImageButton) findViewById(R.id.light_button);
//		System.out.println(lightButton);
	}

	@Override
	public void onResume() {
		super.onResume();
		if(turnedOn) removeNotification();
	}

	@Override
	public void onStop() {
		super.onStop();
		if(turnedOn) sendNotification();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		return id == R.id.action_settings || super.onOptionsItemSelected(item);
		//return (id == (int) R.id.action_settings) || super.onOptionsItemSelected(item);
	}


	@Override
	public void surfaceCreated(SurfaceHolder surfaceHolder) {

	}

	@Override
	public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) {

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder surfaceHolder) {

	}

	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
								 Bundle savedInstanceState) {
			rootView = inflater.inflate(R.layout.fragment_main, container, false);
			ImageButton lightButton = (ImageButton) rootView.findViewById(R.id.light_button);
			if(MainActivity.turnedOn) lightButton.setImageResource(R.drawable.ic_launcher);
			return rootView;
		}
	}

	public void toggleLed(View view) {
		if (ledOn) {
			rootView.setBackgroundResource(R.color.background);
			alert("LED off");
		} else {
			rootView.setBackgroundColor(Color.WHITE);
			alert("LED on");
		}
		ledOn = !ledOn;
	}

	public void toggle(View view) {
		if (lightButton == null) {
			lightButton = (ImageButton) view;
			// lightButton = (ImageButton) findViewById(R.id.light_button);
		}
		if (!isFlashLightAvailable()) {
			alert("Flash light is not available");
			return;
		}
		if (turnedOn) {
			turnOff();
		} else {
			turnOn();
		}
		turnedOn = !turnedOn;
	}

	private void turnOn() {
		if (surfaceHolder == null) {
			SurfaceView surfaceView = (SurfaceView) findViewById(R.id.surface_view);
			if (surfaceView != null) {
				surfaceHolder = surfaceView.getHolder();
				if (surfaceHolder != null) {
					surfaceHolder.addCallback(this);
					surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
				} else alert("surfaceHolder is null");
			} else alert("surfaceView is null");
		}
		try {
			camera = Camera.open();
		} catch (Exception e) {
			e.printStackTrace();
			alert("Camera is not accessible!");
			return;
		}

		Camera.Parameters p = camera.getParameters();
		p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);

		camera.setParameters(p);
		try {
			camera.setPreviewDisplay(surfaceHolder);
		} catch (IOException e) {
			e.printStackTrace();
		}
		camera.startPreview();
		lightButton.setImageResource(R.drawable.ic_launcher);
		alert("light on");
	}

	private void turnOff() {
		if(camera == null){
			alert("camera is null");
			return;
		}
		camera.stopPreview();
		camera.release();
		lightButton.setImageResource(R.drawable.light_off);
		alert("light off");
	}

	private boolean isFlashLightAvailable() {
		return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
	}

	private void alert(String msg) {
		Toast toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
		toast.setGravity(1, 0, 0);
		toast.show();
		System.out.println(msg);
	}

	@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
	private void sendNotification(){
		int id = 1;
		NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
				.setContentTitle("Flash light")
				.setContentText("Flash light is still turned on")
				.setSmallIcon(R.drawable.ic_launcher)
				.setDefaults(0)
				.setLights(Color.MAGENTA, 300, 2000);
		notification.setTicker("Flash light is still turned on");
		Intent resultIntent = new Intent(this, MainActivity.class);

		TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
		stackBuilder.addParentStack(MainActivity.class);
		stackBuilder.addNextIntent(resultIntent);
		PendingIntent resultPendingIntent =
				stackBuilder.getPendingIntent(
						0,
						PendingIntent.FLAG_UPDATE_CURRENT
				);
		notification.setContentIntent(resultPendingIntent);

		NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		notificationManager.notify(id, notification.build());

	}
	private void removeNotification(){
		NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		notificationManager.cancel(1);
	}
}
